package cn.wtg.kotlinlib.baseUi

import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.concurrent.schedule

/**
 * author: wtg
 * time: 2022/11/16
 * desc:
 */
abstract class BaseFragment : Fragment() {
    val TAG = this.javaClass.simpleName
    protected var initView: View? = null
    private var loadingPopupView: LoadingPopupView? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (initView == null) {
            initView = inflater.inflate(getLayoutRes(), container, false)
            initView(savedInstanceState, initView)
        }
        return view
    }

    protected fun showLoading(title: String) {
        CoroutineScope(Dispatchers.Main).launch {
            if (loadingPopupView == null) {
                loadingPopupView = XPopup.Builder(context).dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false).asLoading()
            }
            loadingPopupView?.setTitle(title)
            if (!loadingPopupView?.isShow!!) {
                loadingPopupView!!.show()
            }
        }
    }

    protected fun showLoading() {
        showLoading("")
    }

    protected fun closeLoading() {
        Timer().schedule(200) {
            CoroutineScope(Dispatchers.Main).launch {
                if (loadingPopupView != null && loadingPopupView!!.isShow) {
                    loadingPopupView!!.dismiss()
                }
            }
        }
    }

    /**
     * 获取布局资源
     *
     * @return id
     */
    @LayoutRes
    abstract fun getLayoutRes(): Int

    /**
     * 初始化数据
     *
     * @param savedInstanceState savedInstanceState
     * @param rootView rootView
     */
    abstract fun initView(savedInstanceState: Bundle?, rootView: View?)

    override fun onDestroy() {
        super.onDestroy()
        initView = null
        loadingPopupView = null
    }
}